package sadeptscorecard

import com.portico.dept.solarch.Project

class ProjectMasterController {

    def show = {
        def projectInstance = Project.get(params.id)
    if (!projectInstance || !params.id) {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'project.label', default: 'Project'), params.id])}"
      redirect(action: "list")
    }
    else {
      [projectInstance: projectInstance]
    }
    }

  def list = {
    def projectInstanceList =  Project.findByEndDateGreaterThanEquals(new Date()) ;
    if ( ! projectInstanceList ){
      flash.message = "No Active Projects Found "
    }
    else [projectInstanceList: projectInstanceList]
  }

  def updateProject = {
    def projectInstance = Project.get(params.id)
    if (projectInstance) {
      if (params.version) {
        def version = params.version.toLong()
        if (projectInstance.version > version) {

          projectInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'project.label', default: 'Project')] as Object[], "Another user has updated this Project while you were editing")
          render(view: "show", model: [projectInstance: projectInstance])
          return
        }
      }
      projectInstance.properties = params
      if (!projectInstance.hasErrors() && projectInstance.save(flush: true)) {
        flash.message = "${message(code: 'default.updated.message', args: [message(code: 'project.label', default: 'Project'), projectInstance.id])}"
        redirect(action: "show", id: projectInstance.id)
      }
      else {
        render(view: "show", model: [projectInstance: projectInstance])
      }
    }
    else {
      flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'project.label', default: 'Project'), params.id])}"
      redirect(action: "list", controller:"project")
    }
  }

}
